//
//  HSMessageslistViewModel.swift
//  HomeSchoolDemo
//
//  Created by rimi on 16/10/10.
//  Copyright © 2016年 黄华强. All rights reserved.
//

import UIKit

/// 判断刷新的状态
///
/// - pull: 上拉
/// - drop: 下拉
enum LoadType {
    case pull
    case drop
}

typealias callback = (_ err: Error?, _ isRefresh:Bool) -> ()

class HSMessageslistViewModel {

    //模型数组
    var messages:[HSMessagesViewModel] = []
    //请求数据
    func requestMessage(loadType:LoadType, finished: @escaping callback) {
        let url = "ZH-schoolname-S-getJXNotification"
        let key = userInfo["key"] as! String
        
        let minID = messages.last?.message.not_id ?? 0
        
        
        let id = (loadType == .drop) ? 0 : minID
        
        let lType = (loadType == .drop) ? 1 : 2
        let param = ["key":key,"id":id,"load_type":lType] as [String : Any]
        
        HSNetWorkTools.shared.downloadData(url: url, parameters: param) {[weak self] (data, error) in
            
            guard let data = data as? NSDictionary else {
                HSAlertView.bottomAlertView("网络异常，请检查")
                finished(error,false)
                return
            }
            switch data["result"] as! Int {
            case 0:
                
                //字典转模型
                let dictArray = data["data"] as! [[String:Any]]
                //创建一个保存模型的可变数组
                var modelArr = [HSMessagesViewModel]()
                
                for dict in dictArray {
                    //创建一个模型对象
                    let messagesModel = HSMessagesModel(dict: dict)
                    if let replayArray = messagesModel.replaylist {
                        
                        var replayMArr = [HSReplaylistModel]()
                        for rDict in replayArray {
                            let replayModel = HSReplaylistModel(dict: rDict as! [String : Any])
                            replayMArr.append(replayModel)
                        }
                        messagesModel.replaylist = replayMArr
                    }
                    //消息模型数组
                    modelArr.append(HSMessagesViewModel(model: messagesModel))
                }
                //下拉是覆盖
                //上拉是添加到后面
                if loadType == .drop {
                    self?.messages = modelArr
                    
                } else {
                    self?.messages += modelArr
                }
                
                finished(nil,true)
                
            case 1:
                HSAlertView.bottomAlertView("已经没有更早的数据了")
                finished(nil,false)
            default:
                break
            }
            
        }
        

    }
}
